package com.banciyuan.bcywebview.biz.circles.smooth.fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CircleApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.foldview.FoldLayout;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.circles.smooth.adapter.CircleSmoothTimelineAdapter;
import com.banciyuan.bcywebview.biz.circles.smooth.decoration.PinterestItemOffsetDecoration;
import com.banciyuan.bcywebview.biz.circles.smooth.viewholder.NewestHeaderHolder;
import com.banciyuan.bcywebview.biz.main.mainpage.ground.GroundConstants;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DiscoverData;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Timeline;

/**
 * Created by squall on 2016/6/24.(つд⊂)ｲﾅｲ
 */
public class CircleSmoothPinterestFragment extends CircleBaseSmoothFragment {

    private Map<String, List<Timeline>> mTimelineCache = new HashMap<>();
    private List<Timeline> gridTimelines = new ArrayList<>();
    private List<Timeline> timelineList = new ArrayList<>();
    private List<Timeline> tempMem = new ArrayList<>();
    private DiscoverData discoverData;

    private SwipeRefreshLayout swipeRefreshLayout;

    private RecyclerView recyclerView;
    private String since = "0";
    private String mGroundType = "all";

    private boolean showGridType = false;
    private boolean changing = false;

    private CircleSmoothTimelineAdapter timelineAdapter;
    private int firstVisibleItemPosition;
    private int offset;

    private NewestHeaderHolder header;
    private boolean isRelaEnd;
    private boolean isDataEnd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.circle_smooth_fragment, null);
        initArgs();
        initUi(view);
        initAction();
        return view;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View rootview) {
        header = new NewestHeaderHolder(View.inflate(getActivity(), R.layout.circle_type_selector, null));
        recyclerView = (RecyclerView) rootview.findViewById(R.id.recycle);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe);
        StaggeredGridLayoutManager sg_mangager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(sg_mangager);
        recyclerView.addItemDecoration(new PinterestItemOffsetDecoration(UIUtils.dip2px(4, getActivity())));
        swipeRefreshLayout.setProgressViewOffset(false, UIUtils.dip2px(205, getActivity()) + getOffset(), UIUtils.dip2px(280, getActivity()) + getOffset());
        swipeRefreshLayout.setColorSchemeResources(R.color.pink, R.color.pink);
        timelineAdapter = new CircleSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, header, true);
        recyclerView.setAdapter(timelineAdapter);
    }

    @Override
    protected void initAction() {
        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (!changing) {
                    super.onScrolled(recyclerView, dx, dy);
                    RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
                    StaggeredGridLayoutManager sgl = (StaggeredGridLayoutManager) lm;
                    firstVisibleItemPosition = findMin(sgl.findFirstVisibleItemPositions(null));
                    offset = sgl.getChildAt(firstVisibleItemPosition) != null ? sgl.getChildAt(firstVisibleItemPosition).getTop() : 0;
                    if (dy < 0) {
                        if (firstVisibleItemPosition == 0 && offset > -UIUtils.dip2px(108, getActivity())) {
                            onFoldScrollListener.onScroll(dy);
                        }
                    } else {
                        onFoldScrollListener.onScroll(dy);
                    }
                }
            }

            @Override
            public void onTop() {
                onFoldScrollListener.onTop();
            }

            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                reFresh();
            }
        });

        header.filter_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPop();
            }
        });
        header.change_showType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!loading) {
                    changing = true;
                    showGridType = !showGridType;
                    if (showGridType) {
                        header.change_showType.setImageResource(R.drawable.card_type);
                    } else {
                        header.change_showType.setImageResource(R.drawable.grid_type);
                    }
                    changeFilterData();
                }
            }
        });
    }

    private void showPop() {
        View contentView = View.inflate(getActivity(), R.layout.circle_type_seletor_dialog_layout, null);
        final PopupWindow filterPop = new PopupWindow(contentView, -1, -2, true);
        filterPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        final RelativeLayout[] clickLine = new RelativeLayout[]{
                (RelativeLayout) contentView.findViewById(R.id.all_line),
                (RelativeLayout) contentView.findViewById(R.id.paint_line),
                (RelativeLayout) contentView.findViewById(R.id.writer_line),
                (RelativeLayout) contentView.findViewById(R.id.cos_line),
                (RelativeLayout) contentView.findViewById(R.id.daily_line),
                (RelativeLayout) contentView.findViewById(R.id.group_line)
        };
        defaultSelect(clickLine, mGroundType);
        for (RelativeLayout clickline : clickLine) {
            clickline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGroundType = (String) v.getTag();
                    changeTxt();
                    changeFilterData();
                    if (filterPop.isShowing()) {
                        filterPop.dismiss();
                    }
                }
            });
        }

        contentView.findViewById(R.id.dialoglayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });

        filterPop.showAsDropDown(header.filter_line, 0, 0);
    }

    private void defaultSelect(RelativeLayout[] clickLine, String type) {
        for (RelativeLayout clickline : clickLine) {
            TextView tv = (TextView) clickline.getChildAt(1);
            ImageView iv = (ImageView) clickline.getChildAt(0);
            String tag = (String) clickline.getTag();
            if (type.equals(tag)) {
                iv.setVisibility(View.VISIBLE);
                tv.setSelected(true);
            } else {
                iv.setVisibility(View.GONE);
                tv.setSelected(false);
            }
        }
    }

    private void changeFilterData() {
        try {
            if (null != mTimelineCache.get(mGroundType + showGridType) && mTimelineCache.get(mGroundType + showGridType).size() > 0) {
                since = "0";
                end_flag = false;
                final List<Timeline> filterDatas = mTimelineCache.get(mGroundType + showGridType);
                if (showGridType) {
                    renderGridTimeline(filterDatas);
                } else {
                    renderTimeline(filterDatas);
                }
            } else {
                reFresh();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkEmpty(List<Timeline> tlist) {
        if (tlist != null && tlist.isEmpty()) {
            Timeline timeline = new Timeline();
            timeline.setOtype("empty");
            timeline.setOtype_data("empty");
            tlist.add(timeline);
        }
    }

    private void changeTxt() {
        if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_ALL)) {
            header.type_name.setText(getString(R.string.all));
        } else if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_COSER)) {
            header.type_name.setText(getString(R.string.cos));
        } else if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_DRAWER)) {
            header.type_name.setText(getString(R.string.draw));
        } else if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_WRITER)) {
            header.type_name.setText(getString(R.string.write));
        } else if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_CIRCLE_DAILY)) {
            header.type_name.setText(getString(R.string.newest_things));
        } else if (StringUtil.notNullEqual(mGroundType, GroundConstants.TYPE_GROUP)) {
            header.type_name.setText(getString(R.string.teamdetail_name));
        }
    }

    @Override
    protected void initData() {
        if (showGridType) {
            getGridTypeDate();
        } else {
            if (since.equals("0")) {
                getHeader();
            }
            getCardTypeDate();
        }
    }

    private void getHeader() {
        discoverData = (DiscoverData) getArguments().getSerializable("rela");
        isRelaEnd = true;
        checkend();
    }

    private void getCardTypeDate() {
        loading = true;
        String url = "";
        if (type.equals("tag")) {
            url = HttpUtils.BASE_URL + CircleApi.getTag();
        } else if (type.equals("work")) {
            url = HttpUtils.BASE_URL + CircleApi.getWork();
        } else {
            return;
        }
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.ID, id));
        pairs.add(new BcyPair(HttpUtils.NAME, name));
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SINCE, since));
        pairs.add(new BcyPair(HttpUtils.TAG_FILTER, mGroundType));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray result = jsonObject.getJSONArray("data");
                        tempMem.clear();
                        tempMem = TimelineFactory.createTimeline(result);
                        if (since.equals("0")) {
                            mTimelineCache.put(mGroundType + showGridType, tempMem);
                            checkEmpty(tempMem);
                            isDataEnd = true;
                            checkend();
                        } else {
                            isDataEnd = true;
                            checkend();
                        }
                    }
                } catch (Exception e) {
                    isDataEnd = true;
                    checkend();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDataEnd = true;
                checkend();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void getGridTypeDate() {
        loading = true;
        String url = "";
        if (type.equals("tag")) {
            url = HttpUtils.BASE_URL + CircleApi.getTagFlow();
        } else if (type.equals("work")) {
            url = HttpUtils.BASE_URL + CircleApi.getWorkFlow();
        } else {
            return;
        }
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.ID, id));
        pairs.add(new BcyPair(HttpUtils.NAME, name));
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SINCE, since));
        pairs.add(new BcyPair(HttpUtils.TAG_FILTER, mGroundType));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                        JSONObject jsonObject = new JSONObject(s);
                        Gson gson = new Gson();
                        tempMem.clear();
                        tempMem = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<Timeline>>() {
                                }.getType());
                        if ("0".equals(since)) {
                            mTimelineCache.put(mGroundType + showGridType, tempMem);
                            checkEmpty(tempMem);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    checkend();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                checkend();
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void renderGridTimeline(List<Timeline> tempList) {
        final StaggeredGridLayoutManager sgl = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
        sgl.setSpanCount(2);
        String ctime = processGridTimelineTempCtime(tempList);
        TimelineFactory.popCircleIllegalGridItem(tempList);
        timelineList.clear();
        if ("0".equals(since)) {
            gridTimelines.clear();
        }
        gridTimelines.addAll(tempList);
        if (timelineAdapter == null) {
            timelineAdapter = new CircleSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, header, false);
            recyclerView.setAdapter(timelineAdapter);
        } else {
            if ("0".equals(since)) {
                timelineAdapter.setHeight(0);
                timelineAdapter.setMax(-1);
                timelineAdapter.setLoading(false);
                timelineAdapter.notifyDataSetChanged();
            } else {
                if (!tempList.isEmpty()) {
                    timelineAdapter.notifyItemChanged(timelineAdapter.getItemCount() - 1);
                    timelineAdapter.notifyItemRangeInserted(gridTimelines.size() - tempList.size() + 2, tempList.size());
                }
            }
        }
        if ("0".equals(since) && changing) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    if (firstVisibleItemPosition == 0) {
                        sgl.scrollToPositionWithOffset(firstVisibleItemPosition, offset);
                    }
                    changing = false;
                }
            });
        } else {
            changing = false;
        }
        if (!tempList.isEmpty()) {
            since = ctime;
        } else {
            end_flag = true;
        }
    }

    private String processGridTimelineTempCtime(List<Timeline> tempList) {
        String ctime;
        if (!tempList.isEmpty()) {
            ctime = tempList.get(tempList.size() - 1).getCtime();
        } else {
            ctime = "0";
        }
        return ctime;
    }

    private void addLocalCard(List<Timeline> templist, DiscoverData discoverData) {
        if (templist != null) {
            if (templist.size() > 2) {
                templist.add(2, getPostRankTimeline(discoverData));
            } else {
                templist.add(getPostRankTimeline(discoverData));
            }
        }
    }

    private Timeline getPostRankTimeline(DiscoverData discoverData) {
        Timeline timeline = new Timeline();
        if (discoverData.getPost_rank() != null) {
            timeline.setPost_rank(discoverData.getPost_rank());
            timeline.setOtype_data("local");
            timeline.setOtype("local");
        } else {
            timeline.setOtype_data("illegal_type");
            timeline.setOtype("illegal_type");
        }
        return timeline;
    }

    private void renderTimeline(List<Timeline> templist) {
        final StaggeredGridLayoutManager sgl = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
        sgl.setSpanCount(1);
        String ctime = processTimelineTempCtime(templist);
        gridTimelines.clear();
        if (since.equals("0")) {
            timelineList.clear();
            if (discoverData != null) {
                addLocalCard(templist, discoverData);
            }
        }
        TimelineFactory.popCircleIllegalItem(templist);
        timelineList.addAll(templist);
        if (timelineAdapter == null) {
            if (type.equals("tag")) {
                timelineAdapter = new CircleSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, header, false);
            } else {
                timelineAdapter = new CircleSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, header, false);
            }
            recyclerView.setAdapter(timelineAdapter);
        } else {
            if (since.equals("0")) {
                timelineAdapter.setHeight(0);
                timelineAdapter.setMax(-1);
                timelineAdapter.setLoading(false);
                timelineAdapter.notifyDataSetChanged();
            } else {
                if (!templist.isEmpty()) {
                    timelineAdapter.notifyItemChanged(timelineAdapter.getItemCount() - 1);
                    timelineAdapter.notifyItemRangeInserted(timelineList.size() - templist.size() + 2, templist.size());
                }
            }
        }
        if (since.equals("0") && changing) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    if (firstVisibleItemPosition == 0) {
                        sgl.scrollToPositionWithOffset(firstVisibleItemPosition, offset);
                    }
                    changing = false;
                }
            });
        } else {
            changing = false;
        }
        if (!templist.isEmpty()) {
            since = ctime;
        } else {
            end_flag = true;
        }
    }

    private void checkend() {
        if (showGridType) {
            renderGridTimeline(tempMem);
            loading = false;
            swipeRefreshLayout.setRefreshing(false);
        } else {
            if (isRelaEnd && isDataEnd) {
                renderTimeline(tempMem);
                loading = false;
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

    private String processTimelineTempCtime(List<Timeline> templist) {
        String ctime;
        if (!templist.isEmpty()) {
            if (!TextUtils.isEmpty(templist.get(templist.size() - 1).getPushtime())) {
                ctime = templist.get(templist.size() - 1).getPushtime();
            } else {
                ctime = "0";
            }
            for (Timeline t : templist) {
                List<TagDetail> tlist = new ArrayList<>();
                for (TagDetail tag : t.getTags()) {
                    boolean is_work = StringUtil.notNullEqual(tag.getWid(), id);
                    if (!tag.getTag_name().equalsIgnoreCase(name) && !is_work) {
                        tlist.add(tag);
                    }
                }
                t.setTags(tlist);
            }
        } else {
            ctime = "0";
        }
        return ctime;
    }

    protected void reFresh() {
        try {
            swipeRefreshLayout.setRefreshing(true);
            since = "0";
            loading = false;
            end_flag = false;
            isDataEnd = false;
            isRelaEnd = false;
            initData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void getParentHeight(int height) {
        try {
            if (!isVisibleToUser) {
                offset = height;
                RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
                StaggeredGridLayoutManager sgl = (StaggeredGridLayoutManager) lm;
                if (sgl != null) {
                    int[] nums = sgl.findFirstVisibleItemPositions(new int[sgl.getSpanCount()]);
                    if (findMin(nums) == 0 || findMin(nums) == -1) {
                        sgl.scrollToPositionWithOffset(0, height);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void passParentScrollY(FoldLayout.OnFoldScrollListener onFoldScrollListener) {
        super.passParentScrollY(onFoldScrollListener);
    }

    private int findMin(int[] firstPositions) {
        int min = firstPositions[0];
        for (int value : firstPositions) {
            if (value < min) {
                min = value;
            }
        }
        return min;
    }
}